﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FlowChartDemo
{
    public partial class FormDemo01V1 : FormBase
    {
        public FormDemo01V1()
        {
            InitializeComponent();
            DemoTitle = "第02节随课Demo  Part1";
            DemoNote = "效果：添加【一个】可拖动的矩形";
        }

        /// <summary>
        /// 画矩形
        /// </summary>
        /// <param name="g"></param>
        void DrawRect(Graphics g)
        {
            g.Clear(panel1.BackColor);
            g.FillRectangle(Brushes.Red,Rect);
        }

        /// <summary>
        /// 当前是否有鼠标按下，且有矩形被选中
        /// </summary>
        bool _isMouseDown = false;
        /// <summary>
        /// 最后一次鼠标的位置
        /// </summary>
        Point _lastMouseLocation = Point.Empty;
        /// <summary>
        /// 当前矩形
        /// </summary>
        Rectangle Rect = Rectangle.Empty;


        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (!Rect.IsEmpty)
            {
                MessageBox.Show("已有矩形，无法再次添加");
                return;
            }
            Rect = new Rectangle()
            {
                X = 50,
                Y = 50,
                Width = 100,
                Height = 100,
            };
            //重绘所有矩形
            DrawRect(panel1.CreateGraphics());
        }

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            //当鼠标按下时

            if (Rect.Contains(e.Location))
            {
                //证明鼠标点到了矩形

                //设置状态及选中矩形
                _isMouseDown = true;
                _lastMouseLocation = e.Location;
            }
        }

        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            //当鼠标移动时

            if (_isMouseDown)
            {
                //当且仅当：有鼠标按下且有矩形被选中时，才进行后续操作

                //改变选中矩形的位置信息，随着鼠标移动而移动

                //计算鼠标位置变化信息
                var moveX = e.Location.X - _lastMouseLocation.X;
                var moveY = e.Location.Y - _lastMouseLocation.Y;

                //将选中形状的位置进行同样的变化
                var oldXY = Rect.Location;
                oldXY.Offset(moveX, moveY);
                Rect = new Rectangle(oldXY, Rect.Size);

                //记录当前鼠标位置
                _lastMouseLocation.Offset(moveX, moveY);

                //重绘所有矩形
                DrawRect(panel1.CreateGraphics());
            }

        }

        private void panel1_MouseUp(object sender, MouseEventArgs e)
        {
            //当鼠标松开时
            if (_isMouseDown)
            {
                //当且仅当：有鼠标按下且有矩形被选中时，才进行后续操作

                //重置相关记录信息
                _isMouseDown = false;
                _lastMouseLocation = Point.Empty;
            }
        }
    }


}
